package com.sjcq.demoexample.config.shiro;



import com.sjcq.demoexample.entity.User;
import com.sjcq.demoexample.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class MyselfRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登录的用户信息
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();

        //设置当前用户权限(从数据库查询)
        info.addStringPermission(currentUser.getPower());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("currentUser");

        if(null == user){
            User result = userService.login(token.getUsername());
            SecurityUtils.getSubject().getSession().setAttribute("currentUser",result);
            return new SimpleAuthenticationInfo(result, result.getPassword(), "");
        }
        else if(user.getUsername().equals(token.getUsername())){
            return new SimpleAuthenticationInfo(user, user.getPassword(), "");
        }

        User result = userService.login(token.getUsername());
        SecurityUtils.getSubject().getSession().setAttribute("currentUser",result);
        return new SimpleAuthenticationInfo(result, result.getPassword(), "");
    }
}
